import os
import uuid
from django.conf import settings
from django.core.files.storage import FileSystemStorage

from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import api_view, parser_classes
from rest_framework.response import Response
from rest_framework import status
from .models import McHospital
from .serializers import McHospitalSerializer
from app.common.pagination import StandardResultsSetPagination

from rest_framework.parsers import MultiPartParser, FormParser

ALLOWED_EXTS = {"jpg", "jpeg", "png", "gif", "pdf", "mp4", "zip"}  # 自行增减
MAX_SIZE = 50 * 1024 * 1024  # 50MB


@api_view(["GET"])
def hospital_list(request):
    items = McHospital.objects.all().order_by("-created_time")

    # 分页
    paginator = StandardResultsSetPagination()
    result_page = paginator.paginate_queryset(items, request)
    serializer = McHospitalSerializer(result_page, many=True)

    return paginator.get_paginated_response(serializer.data)


@api_view(["GET"])
def hospital_detail(request, pk):
    try:
        item = McHospital.objects.get(pk=pk)
    except McHospital.DoesNotExist:
        return Response({"error": "Not found"}, status=status.HTTP_404_NOT_FOUND)
    serializer = McHospitalSerializer(item)
    return Response(serializer.data)


@api_view(["POST"])
def hospital_create(request):
    serializer = McHospitalSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(["PUT"])
def hospital_update(request, pk):
    try:
        item = McHospital.objects.get(pk=pk)
    except McHospital.DoesNotExist:
        return Response({"error": "Not found"}, status=status.HTTP_404_NOT_FOUND)
    serializer = McHospitalSerializer(item, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(["DELETE"])
def hospital_delete(request, pk):
    try:
        item = McHospital.objects.get(pk=pk)
    except McHospital.DoesNotExist:
        return Response({"error": "Not found"}, status=status.HTTP_404_NOT_FOUND)
    item.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)


def _safe_filename(filename: str) -> str:
    # 生成不重复文件名：<uuid>.<ext>
    ext = filename.split(".")[-1].lower() if "." in filename else ""
    return f"{uuid.uuid4().hex}.{ext}" if ext else uuid.uuid4().hex


def _validate(file_obj):
    # 大小校验
    if file_obj.size > MAX_SIZE:
        return False, f"文件过大，超过 {MAX_SIZE // (1024*1024)}MB 限制"
    # 后缀校验
    name = file_obj.name
    if "." in name:
        ext = name.rsplit(".", 1)[-1].lower()
        if ALLOWED_EXTS and ext not in ALLOWED_EXTS:
            return False, f"不允许的文件类型 .{ext}"
    return True, None


@api_view(["POST"])
@parser_classes([MultiPartParser, FormParser])
def upload_file(request):
    """
    接收 form-data: file=<二进制>
    返回：{"url": "<完整访问URL>", "path": "<相对路径>", "name": "<保存名>", "size": <字节>}
    """
    file_obj = request.FILES.get("file")
    if not file_obj:
        return Response(
            {"detail": "请使用 form-data 传递字段 file"},
            status=status.HTTP_400_BAD_REQUEST,
        )

    ok, msg = _validate(file_obj)
    if not ok:
        return Response({"detail": msg}, status=status.HTTP_400_BAD_REQUEST)

    # 确保 FILE_ROOT 存在
    os.makedirs(settings.FILE_ROOT, exist_ok=True)

    # 保存文件
    fs = FileSystemStorage(location=settings.FILE_ROOT, base_url=settings.FILE_URL)
    filename = _safe_filename(file_obj.name)
    saved_name = fs.save(filename, file_obj)  # 返回相对 FILE_ROOT 的路径
    rel_path = saved_name.replace("\\", "/")

    # 生成完整访问 URL
    file_url = request.build_absolute_uri(fs.url(rel_path))

    return Response(
        {
            "url": file_url,
            "path": settings.FILE_URL + rel_path,
            "name": os.path.basename(rel_path),
            "size": file_obj.size,
        }
    )
